package executor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

//    6-8   支持关闭操作的Web服务器
public class LifecycleWebServer {
    private final ExecutorService exec = Executors.newCachedThreadPool(); //新建可缓存的线程池

    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()) {     //只要未被关闭，exec.isShutdown当关闭返回true
            try {
                final Socket conn = socket.accept();
                exec.execute(new Runnable() {
                    public void run() {
                        handleRequest(conn);
                    }
                });
            } catch (RejectedExecutionException e) { //在关闭后提交的任务，会抛出异常
                if (!exec.isShutdown())      //如果还没关闭
                    log("task submission rejected", e);
            }
        }

        exec.shutdownNow();
    }

    public void stop() {
        //不再接受新的任务，同时等待已经提交的任务执行完成——包括还未开始执行的任务
        exec.shutdown();
    }

    private void log(String msg, Exception e) {
        //创建一个匿名的记录器
        Logger.getAnonymousLogger().log(Level.WARNING, msg, e);
    }

    void handleRequest(Socket connection) {
        Request req = readRequest(connection);
        if (isShutdownRequest(req))
            //不再接受新的任务，同时等待已经提交的任务执行完成——包括还未开始执行的任务
            stop();
        else
            dispatchRequest(req);
    }

    interface Request {
    }

    private Request readRequest(Socket s) {      //读取ExecutorService生命周期的状态
        return null;
    }

    private void dispatchRequest(Request r) {
    }

    private boolean isShutdownRequest(Request r) {  //已被关闭的请求
        return false;
    }
}
